using System;
using System.Runtime.Serialization;
using System.Collections.ObjectModel;
using System.Windows.Documents;
using System.Collections.Specialized;
using System.Linq;
namespace FuzzyTaskList
{
    [DataContract]
    public class TaskSet
    {
        public TaskSet()
        {
            Version = "1.0";
            TaskCollection = new ObservableCollection<FuzzyTaskItem>();
            TaskCollection.CollectionChanged += TaskCollection_CollectionChanged;
            StartDate = DateTime.Now.Date;
        }
        [OnDeserialized]
        private void OnDeserialized(StreamingContext c)
        {
            StartDate = GetMinStartDateInTaskList();

            TaskCollection.CollectionChanged += TaskCollection_CollectionChanged;
            foreach (FuzzyTaskItem fti in TaskCollection)
            {
                fti.StartDateChanged += tfi_StartDateChanged;
                fti.TaskSetStartDate = StartDate;
                fti.ComputeHistoryView();
            }
        }


        void TaskCollection_CollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            if (e.Action == NotifyCollectionChangedAction.Add)
            {
                foreach (FuzzyTaskItem tfi in e.NewItems)
                {
                    tfi.StartDateChanged += tfi_StartDateChanged;
                }
            }
        }

        void tfi_StartDateChanged(object sender, EventArgs e)
        {

            var smallestStartDate = GetMinStartDateInTaskList();
            if (StartDate != smallestStartDate)
            {
                StartDate = smallestStartDate;
                foreach (FuzzyTaskItem fti in TaskCollection)
                {
                    fti.TaskSetStartDate = StartDate;
                    fti.ComputeHistoryView();
                }
            }
        }

        private DateTime GetMinStartDateInTaskList()
        {
            DateTime min = DateTime.MaxValue;
            foreach (FuzzyTaskItem fti in TaskCollection)
            {
                if (fti.StartDate < min)
                    min = fti.StartDate;
            }
            return min;
//            return TaskCollection.Aggregate(DateTime.MaxValue, (min, next_fti) => next_fti.StartDate < min ? next_fti.StartDate : min);
        }
        [DataMember]
        public ObservableCollection<FuzzyTaskItem> TaskCollection { get; private set; }

        [DataMember]
        public string Version { get; set; }
        [DataMember]
        public DateTime StartDate { get; set; }




    }
}
